package com.buka.recipe.system.controller;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.buka.recipe.common.result.Result;
import com.buka.recipe.common.result.ResultGenerator;
import com.buka.recipe.common.utils.TreeUtils;
import com.buka.recipe.system.entity.Department;
import com.buka.recipe.system.service.DepartmentService;
import com.buka.recipe.system.vo.DepartmentVo;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Log4j2
@RestController
@RequestMapping("/system/department")
public class DepartmentController {

    private final DepartmentService departmentService;

    @Autowired
    public DepartmentController(DepartmentService departmentService) {
        this.departmentService = departmentService;
    }

    @PostMapping("/add")
    public Result<?> add(@RequestBody JSONObject params) {
        String name = params.getString("name").trim();
        int parentId = params.getIntValue("parentId", 0);
        if (!StringUtils.hasLength(name)) {
            return ResultGenerator.genFailResult("部门名称不能为空");
        }
        Department department = departmentService.getDepartmentByNameAndParentId(name, parentId);
        if (department != null) {
            return ResultGenerator.genFailResult("部门已存在");
        }
        String parentLevel = "0";
        if (parentId > 0) {
            Department parentDepartment = departmentService.getDepartmentById(parentId);
            if (parentDepartment == null) {
                return ResultGenerator.genFailResult("上级部门不存在或无权限操作此部门");
            } else {
                parentLevel = parentDepartment.getLevel();
            }
        }
        department = new Department();
        department.setName(name);
        departmentService.save(department);
        department.setParentId(parentId);
        department.setLevel(parentLevel + "/" + department.getId());
        department.setCreateDate(new Date());
        departmentService.save(department);
        return ResultGenerator.genSuccessResult();
    }

    @PostMapping("/del")
    public Result<?> del(@RequestBody JSONObject params) {
        Integer id = params.getInteger("id");
        Boolean confirm = params.getBoolean("confirm");
        // 如果 confirm 为 true， 强制删除，包含子部门一起删除
        Department department = departmentService.getDepartmentById(id);
        if (department == null) {
            return ResultGenerator.genFailResult("部门不存在或无权限操作此部门");
        }
        try {
            departmentService.delete(department, confirm);
        } catch (Exception e) {
            return ResultGenerator.genFailResult("删除失败, 请确认部门下是否包含子部门、账号等。");
        }
        return ResultGenerator.genSuccessResult();
    }

    @GetMapping("/list")
    public Result<?> list(@RequestParam(required = false) Integer parentId,
                          @RequestParam(required = false) String name,
                          @RequestParam(required = false, defaultValue = "0") Integer current,
                          @RequestParam(required = false, defaultValue = "10") Integer pageSize) {
        Page<Department> departments = departmentService.getAll(parentId, name, current, pageSize);
        return ResultGenerator.genSuccessResult(departments.map(item -> {
            DepartmentVo departmentVo = new DepartmentVo();
            BeanUtils.copyProperties(item, departmentVo);
            Department department = departmentService.getDepartmentById(item.getParentId());
            departmentVo.setParentName(department != null ? department.getName() : null);
            return departmentVo;
        }));
    }

    @GetMapping("/tree")
    public Result<?> tree(@RequestParam(required = false) Integer parentId,
                          @RequestParam(required = false) String name,
                          @RequestParam(required = false, defaultValue = "0") Integer current,
                          @RequestParam(required = false, defaultValue = "10") Integer pageSize) {
        Page<Department> departments = departmentService.getAll(parentId, name, current, pageSize);
        JSONArray departmentVos = TreeUtils.listToJsonTree(departments.stream().toList(), "id", "parentId", "children");
        return ResultGenerator.genSuccessResult(departmentVos);
    }

    @PostMapping("/update")
    public Result<?> update(@RequestBody Department department) {
        if (department.getId() == null) {
            log.error("参数错误，ID不能为空");
            return ResultGenerator.genFailResult("参数错误，ID不能为空");
        }
        if (!StringUtils.hasLength(department.getName())) {
            log.error("参数错误，名称不能为空");
            return ResultGenerator.genFailResult("参数错误，名称不能为空");
        }
        Department d = departmentService.getDepartmentById(department.getId());
        if (d == null) {
            return ResultGenerator.genFailResult("部门不存在或无权限操作此部门");
        }
        if (!d.getName().equals(department.getName())) {
            d.setName(department.getName());
        }
        // 需要修改的部门列表
        List<Department> updateDepartments = new ArrayList<>();

        if (!department.getParentId().equals(d.getParentId())) {
            // 修改了上级部门, 所有子部门的 level 都需要修改
            String parentLevel = "0";
            int parentId = department.getParentId();
            if (parentId < 0) {
                return ResultGenerator.genFailResult("上级部门选择错误");
            }
            if (parentId > 0) {
                Department parentDepartment = departmentService.getDepartmentById(parentId);
                if (parentDepartment == null) {
                    return ResultGenerator.genFailResult("上级部门不存在或无权限操作此部门");
                } else {
                    parentLevel = parentDepartment.getLevel();
                }
            }

            d.setParentId(parentId);
            d.setLevel(parentLevel + "/" + d.getId());

            // 得到当前部门的子部门列表
            List<Department> subDepartments = departmentService.getSubDepartmentsById(d.getId());
            if (subDepartments != null && !subDepartments.isEmpty()) {
                // 有子部门
                subDepartments.forEach(subDepartment -> {
                    subDepartment.setLevel(d.getLevel() + "/" + subDepartment.getId());
                    updateDepartments.add(subDepartment);
                });
            }

        }
        updateDepartments.add(d);
        departmentService.updateAll(updateDepartments);
        return ResultGenerator.genSuccessResult();
    }

}
